package org.atf.services;

import java.util.List;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.directwebremoting.Browser;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.ScriptSessionFilter;
import org.directwebremoting.ScriptSessions;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.impl.DaemonThreadFactory;

public class NotificationUpdater implements Runnable{

	
	public NotificationUpdater() {
		ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1,new DaemonThreadFactory());
		executor.scheduleAtFixedRate(this, 0, 5, TimeUnit.SECONDS);
		// TODO Auto-generated constructor stub
	}

	public void run() {
		// TODO Auto-generated method stub
		List<TaskStatus> notifyTasks=TaskManager.getInstance().getAllNotifications();
		for(TaskStatus ts: notifyTasks){
			ts.setTaskId("N"+ts.getTaskId());
		}
		for(TaskStatus ts: notifyTasks){
			notifyAll(ts);		
			try {
				Thread.sleep(100L);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private void notifyAll(final TaskStatus ts) {
		// TODO Auto-generated method stub
		Integer serverId=ts.getServerId();
		Browser.withAllSessionsFiltered(new ServerEnabledFilter(serverId),new Runnable(){

			public void run() {
				// TODO Auto-generated method stub
				
				ScriptSessions.addFunctionCall("uft.addNotificationEntry", ts);
			}
			
		});
	}
	
	public class ServerEnabledFilter implements ScriptSessionFilter {
		 
		 private Integer serverId;
		 
		 public ServerEnabledFilter(Integer serverId){
			 this.serverId=serverId;
		 }

		public boolean match(ScriptSession arg0) {
			// TODO Auto-generated method stub
			Object check = arg0.getAttribute(SERVER_ID_SESSION_ATTR);
			Object notifyEnabled = arg0.getAttribute(ENABLE_NOTIFICATION);
			if(check != null &&  notifyEnabled != null){
				List<Integer> serverIds=(List<Integer>) check;
				Boolean notify= (Boolean)notifyEnabled;
				if(serverIds.contains(serverId) && notify){
					return true;
				}
			}
			return false;
		}
		 
	 }
	 public void enableNotification() {
	        ScriptSession scriptSession = WebContextFactory.get().getScriptSession();
	        scriptSession.setAttribute(ENABLE_NOTIFICATION, true);
	 }
	 
	 public void disableNotification() {
	        ScriptSession scriptSession = WebContextFactory.get().getScriptSession();
	        scriptSession.setAttribute(ENABLE_NOTIFICATION, false);
	 }
	
	 private final static String SERVER_ID_SESSION_ATTR = "SERVER_ID_SESSION_ATTR";
	 private final static String ENABLE_NOTIFICATION = "ENABLE_NOTIFICATION";

}
